<template>
    <div class="admin-files">
        <h1>文件管理</h1>

        <el-tabs v-model="activeTab" class="file-tabs">
            <el-tab-pane label="全部文件" name="all">
                <div class="toolbar">
                    <el-input v-model="searchQuery" placeholder="搜索文件名" class="search-input" clearable
                        @clear="handleSearch">
                        <template #suffix>
                            <el-icon class="el-input__icon" @click="handleSearch">
                                <Search />
                            </el-icon>
                        </template>
                    </el-input>

                    <div class="filter-group">
                        <div class="filter-label">文件类型：</div>
                        <el-select v-model="fileTypeFilter" placeholder="文件类型" clearable @change="handleFilterChange">
                            <el-option label="全部" value="" />
                            <el-option label="文档" value="document" />
                            <el-option label="图片" value="image" />
                            <el-option label="视频" value="video" />
                            <el-option label="音频" value="audio" />
                            <el-option label="压缩包" value="archive" />
                            <el-option label="其他" value="other" />
                        </el-select>

                        <div class="filter-label">排序方式：</div>
                        <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange">
                            <el-option label="上传时间 ↓" value="uploadTime-desc" />
                            <el-option label="上传时间 ↑" value="uploadTime-asc" />
                            <el-option label="文件大小 ↓" value="fileSize-desc" />
                            <el-option label="文件大小 ↑" value="fileSize-asc" />
                            <el-option label="下载次数 ↓" value="downloads-desc" />
                        </el-select>
                    </div>
                </div>

                <el-table :data="fileList" style="width: 100%" v-loading="loading">
                    <el-table-column prop="fileName" label="文件名" min-width="200">
                        <template #default="scope">
                            <div class="file-name-cell">
                                <el-icon class="file-icon">
                                    <Document v-if="scope.row.fileType === 'document'" />
                                    <Picture v-else-if="scope.row.fileType === 'image'" />
                                    <VideoPlay v-else-if="scope.row.fileType === 'video'" />
                                    <Headset v-else-if="scope.row.fileType === 'audio'" />
                                    <Folder v-else-if="scope.row.fileType === 'archive'" />
                                    <Files v-else />
                                </el-icon>
                                <el-tooltip :content="scope.row.fileName" placement="top" :show-after="1000">
                                    <span class="file-name">{{ scope.row.fileName }}</span>
                                </el-tooltip>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="fileSize" label="大小" width="120">
                        <template #default="scope">
                            {{ formatFileSize(scope.row.fileSize) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="fileType" label="文件类型" width="100">
                        <template #default="scope">
                            <el-tag size="small" :type="getFileTypeTagType(scope.row.fileType)">
                                {{ getFileTypeText(scope.row.fileType) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="上传时间" width="180">
                        <template #default="scope">
                            {{ formatDate(scope.row.createTime) }}
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="createTime" label="过期时间">
                        <template #default="scope">
                            {{ scope.row.expireTime ? formatDate(scope.row.expireTime) : -1 }}
                        </template>
                    </el-table-column> -->
                    <el-table-column prop="uploaderName" label="上传者" />
                    <el-table-column prop="downloadCount" label="下载次数" align="center" />
                    <el-table-column prop="accessCode" label="访问码" width="100" align="center">
                        <template #default="scope">
                            <span class="access-code">{{ scope.row.accessCode }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="文件状态" width="100" align="center">
                        <template #default="scope">
                            <el-tag :type="getStatusTagType(scope.row.status)">
                                {{ getStatusText(scope.row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="auditStatus" label="审核状态">
                        <template #default="scope">
                            <el-tag :type="getStatusTagType(scope.row.auditStatus)">
                                {{ getStatusText(scope.row.auditStatus) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" width="220">
                        <template #default="scope">
                            <el-button size="small" @click="handlePreview(scope.row)">
                                <el-icon>
                                    <View />
                                </el-icon>
                            </el-button>
                            <el-button size="small" @click="handleDownload(scope.row)">
                                <el-icon>
                                    <Download />
                                </el-icon>
                            </el-button>
                            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                                <el-icon>
                                    <Edit />
                                </el-icon>
                            </el-button>
                            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="pagination-container">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </el-tab-pane>

            <el-tab-pane label="待审核文件" name="pending">
                <el-table :data="pendingFiles" style="width: 100%" v-loading="pendingLoading">
                    <el-table-column prop="fileName" label="文件名" min-width="150">
                        <template #default="scope">
                            <div class="file-name-cell">
                                <el-icon class="file-icon">
                                    <Document v-if="scope.row.fileType === 'document'" />
                                    <Picture v-else-if="scope.row.fileType === 'image'" />
                                    <VideoPlay v-else-if="scope.row.fileType === 'video'" />
                                    <Headset v-else-if="scope.row.fileType === 'audio'" />
                                    <Folder v-else-if="scope.row.fileType === 'archive'" />
                                    <Files v-else />
                                </el-icon>
                                <el-tooltip :content="scope.row.fileName" placement="top" :show-after="1000">
                                    <span class="file-name">{{ scope.row.fileName }}</span>
                                </el-tooltip>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="fileSize" label="大小" width="120">
                        <template #default="scope">
                            {{ formatFileSize(scope.row.fileSize) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="fileType" label="文件类型" width="100">
                        <template #default="scope">
                            <el-tag size="small" :type="getFileTypeTagType(scope.row.fileType)">
                                {{ getFileTypeText(scope.row.fileType) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="uploadTime" label="上传时间">
                        <template #default="scope">
                            {{ formatDate(scope.row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="uploaderName" label="上传者" />
                    <el-table-column prop="accessCode" label="访问码" width="100" align="center">
                        <template #default="scope">
                            <span class="access-code">{{ scope.row.accessCode }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="auditStatus" label="审核状态">
                        <template #default="scope">
                            <el-tag :type="getStatusTagType(scope.row.auditStatus)">
                                {{ getStatusText(scope.row.auditStatus) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" width="250">
                        <template #default="scope">
                            <el-button size="small" @click="handlePreview(scope.row)">
                                <el-icon>
                                    <View />
                                </el-icon>
                            </el-button>
                            <el-button size="small" type="success" @click="handleApprove(scope.row)">
                                <el-icon>
                                    <Check />
                                </el-icon> 通过
                            </el-button>
                            <el-button size="small" type="danger" @click="handleReject(scope.row)">
                                <el-icon>
                                    <Close />
                                </el-icon> 拒绝
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="pagination-container">
                    <el-pagination v-model:current-page="pendingCurrentPage" v-model:page-size="pendingPageSize"
                        :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next" :total="pendingTotal"
                        @size-change="handlePendingSizeChange" @current-change="handlePendingCurrentChange" />
                </div>
            </el-tab-pane>
        </el-tabs>

        <!-- 文件编辑对话框 -->
        <el-dialog v-model="dialogVisible" title="编辑文件信息" width="500px">
            <el-form :model="fileForm" :rules="rules" ref="fileFormRef" label-width="100px">
                <el-form-item label="文件名" prop="fileName">
                    <el-input v-model="fileForm.fileName" />
                </el-form-item>
                <el-form-item label="访问码" prop="accessCode">
                    <el-input v-model="fileForm.accessCode" maxlength="4" show-word-limit />
                </el-form-item>
                <el-form-item label="文件状态" prop="status">
                    <el-select v-model="fileForm.status" placeholder="请选择状态">
                        <el-option label="正常" value="active" />
                        <el-option label="禁用" value="disabled" />
                    </el-select>
                </el-form-item>
                <el-form-item label="审核状态" prop="auditStatus">
                    <el-select v-model="fileForm.auditStatus" placeholder="请选择状态">
                        <el-option label="已通过" value="approved" />
                        <el-option label="待审核" value="pending" />
                        <el-option label="已拒绝" value="rejected" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitFileForm">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 审核拒绝原因对话框 -->
        <el-dialog v-model="rejectDialogVisible" title="拒绝原因" width="500px">
            <el-form :model="rejectForm" :rules="rejectRules" ref="rejectFormRef" label-width="100px">
                <el-form-item label="拒绝原因" prop="reason">
                    <el-select v-model="rejectForm.reasonType" placeholder="选择拒绝原因类型" @change="handleReasonTypeChange">
                        <el-option label="违规内容" value="violation" />
                        <el-option label="侵权内容" value="copyright" />
                        <el-option label="恶意软件" value="malware" />
                        <el-option label="其他原因" value="other" />
                    </el-select>
                </el-form-item>
                <el-form-item label="详细说明" prop="detail">
                    <el-input v-model="rejectForm.detail" type="textarea" rows="4" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="rejectDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitRejectForm">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 文件预览对话框 -->
        <el-dialog v-model="previewDialogVisible" :title="previewFile?.fileName || '文件预览'" width="800px" top="5vh"
            destroy-on-close class="preview-dialog">
            <div v-loading="previewLoading" class="preview-container">
                <div class="preview-wrapper">
                    <!-- 文件信息栏 -->
                    <div class="file-info-bar" v-if="previewFile">
                        <div class="file-info">
                            <el-icon class="file-icon" :size="20">
                                <Document v-if="previewFile.fileType === 'document'" />
                                <Picture v-else-if="previewFile.fileType === 'image'" />
                                <VideoPlay v-else-if="previewFile.fileType === 'video'" />
                                <Headset v-else-if="previewFile.fileType === 'audio'" />
                                <Folder v-else-if="previewFile.fileType === 'archive'" />
                                <Files v-else />
                            </el-icon>
                            <span class="file-name">{{ previewFile.fileName }}</span>
                            <el-tag size="small" :type="getFileTypeTagType(previewFile.fileType)" class="file-type-tag">
                                {{ getFileTypeText(previewFile.fileType) }}
                            </el-tag>
                            <span class="file-size">{{ formatFileSize(previewFile.fileSize) }}</span>
                        </div>
                        <div class="file-actions">
                            <el-button size="small" @click="handleDownload(previewFile)">
                                <el-icon>
                                    <Download />
                                </el-icon> 下载
                            </el-button>
                        </div>
                    </div>

                    <!-- 图片预览 -->
                    <div v-if="previewFile?.fileType === 'image'" class="preview-content image-preview">
                        <img :src="previewUrl" alt="图片预览" @load="previewLoading = false" />
                    </div>

                    <!-- 文档预览 -->
                    <div v-else-if="previewFile?.fileType === 'document'" class="preview-content document-preview">
                        <!-- PDF预览 -->
                        <div v-if="previewFile.fileName.toLowerCase().endsWith('.pdf')" class="pdf-container">
                            <iframe :src="previewUrl" frameborder="0" width="100%" height="100%"
                                @load="previewLoading = false"></iframe>
                        </div>

                        <!-- 文本文件预览 -->
                        <div v-else-if="isTextFile(previewFile.fileName)" class="text-preview" v-loading="textLoading">
                            <pre v-if="textContent" class="text-content">{{ textContent }}</pre>
                            <div v-else class="text-fallback">
                                <el-button type="primary" @click="loadTextContent(previewFile)">
                                    <el-icon>
                                        <View />
                                    </el-icon> 加载文本内容
                                </el-button>
                            </div>
                        </div>

                        <!-- 代码文件预览 -->
                        <div v-else-if="isCodeFile(previewFile.fileName)" class="code-preview" v-loading="textLoading">
                            <pre v-if="textContent" class="code-content"
                                :class="getCodeLanguageClass(previewFile.fileName)">{{
                                    textContent }}</pre>
                            <div v-else class="code-fallback">
                                <el-button type="primary" @click="loadTextContent(previewFile)">
                                    <el-icon>
                                        <View />
                                    </el-icon> 加载代码内容
                                </el-button>
                            </div>
                        </div>

                        <!-- 其他文档类型 -->
                        <div v-else class="document-fallback">
                            <el-icon :size="48">
                                <Document />
                            </el-icon>
                            <p>此文档类型暂不支持在线预览</p>
                            <el-button type="primary" @click="handleDownload(previewFile)">
                                <el-icon>
                                    <Download />
                                </el-icon> 下载文件
                            </el-button>
                        </div>
                    </div>

                    <!-- 视频预览 -->
                    <div v-else-if="previewFile?.fileType === 'video'" class="preview-content video-preview">
                        <div class="video-container"
                            style="width: 100%; display: flex; justify-content: center; align-items: center;">
                            <video controls @loadeddata="previewLoading = false">
                                <source :src="previewUrl"
                                    :type="`video/${previewFile.fileName.split('.').pop().toLowerCase()}`">
                                您的浏览器不支持视频播放
                            </video>
                        </div>
                    </div>

                    <!-- 音频预览 -->
                    <div v-else-if="previewFile?.fileType === 'audio'" class="preview-content audio-preview">
                        <div class="audio-container"
                            style="width: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
                            <el-icon :size="36" class="audio-icon">
                                <Headset />
                            </el-icon>
                            <audio controls @loadeddata="previewLoading = false">
                                <source :src="previewUrl"
                                    :type="`audio/${previewFile.fileName.split('.').pop().toLowerCase()}`">
                                您的浏览器不支持音频播放
                            </audio>
                        </div>
                    </div>

                    <!-- 压缩包预览 -->
                    <div v-else-if="previewFile?.fileType === 'archive'" class="archive-preview">
                        <div class="archive-info">
                            <el-icon :size="48">
                                <Folder />
                            </el-icon>
                            <h3>{{ previewFile?.fileName }}</h3>
                            <p>文件类型: {{ getFileTypeText(previewFile?.fileType) }}</p>
                            <p>文件大小: {{ formatFileSize(previewFile?.fileSize) }}</p>
                        </div>
                        <div v-if="archiveContents.length > 0" class="archive-contents">
                            <h4>压缩包内容</h4>
                            <el-table :data="archiveContents" style="width: 100%">
                                <el-table-column prop="name" label="文件名" min-width="200" />
                                <el-table-column prop="size" label="大小" width="120">
                                    <template #default="scope">
                                        {{ formatFileSize(scope.row.size) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="lastModified" label="修改时间" width="180">
                                    <template #default="scope">
                                        {{ scope.row.lastModified ? formatDate(scope.row.lastModified) : '-' }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="isDirectory" label="类型" width="120">
                                    <template #default="scope">
                                        <el-tag size="small"
                                            :type="scope.row.isDirectory ? 'info' : getFileTypeTagByExt(scope.row.name)">
                                            {{ scope.row.isDirectory ? '目录' : getFileTypeByExt(scope.row.name) }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <div v-else class="archive-actions">
                            <el-button type="primary" @click="loadArchiveContents(previewFile)">
                                <el-icon>
                                    <View />
                                </el-icon> 查看压缩包内容
                            </el-button>
                            <el-button type="primary" @click="handleDownload(previewFile)">
                                <el-icon>
                                    <Download />
                                </el-icon> 下载文件
                            </el-button>
                        </div>
                    </div>

                    <!-- 其他文件类型 -->
                    <div v-else class="other-preview">
                        <div class="other-info">
                            <el-icon :size="48">
                                <Failed />
                            </el-icon>
                        </div>
                        <h1>此文件不支持预览请下载后查看</h1>
                        <div class="preview-actions">
                            <el-button type="primary" @click="handleDownload(previewFile)">
                                <el-icon>
                                    <Download />
                                </el-icon> 下载文件
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Document, Picture, VideoPlay, Headset, Folder, Files, Download, Edit, Delete, View, Check, Close, Failed } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/utils/request'
import list from '@/utils/url'
import { formatFileSize } from '@/utils/commonUtils'

// 标签页
const activeTab = ref('all')

// 文件列表数据
const fileList = ref([])

// 待审核文件
const pendingFiles = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(5)

const pendingCurrentPage = ref(1)
const pendingPageSize = ref(10)
const pendingTotal = ref(3)

// 搜索和筛选相关
const searchQuery = ref('')
const fileTypeFilter = ref('')
const sortBy = ref('uploadTime-desc')
const loading = ref(false)
const pendingLoading = ref(false)

// 表单相关
const dialogVisible = ref(false)
const fileFormRef = ref(null)
const fileForm = ref({
    id: null,
    fileName: '',
    accessCode: '',
    status: 'active',
    auditStatus: 'pending'
})

// 表单验证规则
const rules = {
    fileName: [
        { required: true, message: '请输入文件名', trigger: 'blur' }
    ],
    accessCode: [
        { required: true, message: '请输入访问码', trigger: 'blur' },
        { min: 4, max: 4, message: '访问码必须为4个字符', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ],
    auditStatus: [
        { required: true, message: '请选择审核状态', trigger: 'change' }
    ]
}

// 拒绝表单相关
const rejectDialogVisible = ref(false)
const rejectFormRef = ref(null)
const rejectForm = ref({
    fileId: null,
    reasonType: '',
    detail: ''
})
const rejectRules = {
    reasonType: [
        { required: true, message: '请选择拒绝原因类型', trigger: 'change' }
    ],
    detail: [
        { required: true, message: '请输入详细说明', trigger: 'blur' }
    ]
}

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleString()
}

// 获取状态标签类型
const getStatusTagType = (status) => {
    switch (status) {
        case 'active': return 'success'
        case 'disabled': return 'info'
        case 'pending': return 'warning'
        case 'expired': return 'danger'
        case 'used': return 'primary'
        case 'deleted': return 'danger'
        case 'approved': return 'success'
        case 'rejected': return 'danger'
        default: return 'info'
    }
}

// 获取状态文本
const getStatusText = (status) => {
    switch (status) {
        case 'active': return '正常'
        case 'disabled': return '禁用'
        case 'pending': return '待审核'
        case 'expired': return '已过期'
        case 'used': return '已使用'
        case 'deleted': return '已删除'
        case 'approved': return '已通过'
        case 'rejected': return '已拒绝'
        default: return '未知'
    }
}

// 获取文件类型标签类型
const getFileTypeTagType = (fileType) => {
    switch (fileType) {
        case 'document': return 'primary'
        case 'image': return 'success'
        case 'video': return 'warning'
        case 'audio': return 'danger'
        case 'archive': return 'info'
        default: return ''
    }
}

// 获取文件类型文本
const getFileTypeText = (fileType) => {
    switch (fileType) {
        case 'document': return '文档'
        case 'image': return '图片'
        case 'video': return '视频'
        case 'audio': return '音频'
        case 'archive': return '压缩包'
        case 'other': return '其他'
        default: return '未知'
    }
}

// 获取文件列表
const fetchFileList = () => {
    loading.value = true

    // 构建查询参数
    let params = {
        fileName: searchQuery.value || undefined,
        fileType: fileTypeFilter.value || undefined,
        sortBy: sortBy.value || undefined
    }

    // 调用API获取文件列表
    http.get(`${list.list_admin_api.getFilesByPage}/${currentPage.value}/${pageSize.value}`, params)
        .then(response => {
            if (response.code === 200) {
                const data = response.data
                fileList.value = data.records
                total.value = data.total
            } else {
                ElMessage.error('获取文件列表失败：' + response.msg)
            }
        })
        .catch(error => {
            console.error('获取文件列表出错：', error)
            ElMessage.error('获取文件列表失败，请稍后重试')
        })
        .finally(() => {
            loading.value = false
        })
}

// 获取待审核文件
const fetchPendingFiles = () => {
    pendingLoading.value = true

    // 调用API获取待审核文件列表
    http.get(`${list.list_admin_api.getFilesByPage}/${pendingCurrentPage.value}/${pendingPageSize.value}`,
        { auditStatus: 'pending' }
    ).then(response => {
        if (response.code === 200) {
            const data = response.data
            pendingFiles.value = data.records
            pendingTotal.value = data.total
        } else {
            ElMessage.error('获取待审核文件失败：' + response.data.msg)
        }
    })
        .catch(error => {
            console.error('获取待审核文件出错：', error)
            ElMessage.error('获取待审核文件失败，请稍后重试')
        })
        .finally(() => {
            pendingLoading.value = false
        })
}

// 处理搜索
const handleSearch = () => {
    currentPage.value = 1
    fetchFileList()
}

// 处理排序变化
const handleSortChange = () => {
    fetchFileList()
}

// 处理筛选变化
const handleFilterChange = () => {
    currentPage.value = 1
    fetchFileList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
    pageSize.value = val
    fetchFileList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchFileList()
}

// 处理待审核文件分页大小变化
const handlePendingSizeChange = (val) => {
    pendingPageSize.value = val
    fetchPendingFiles()
}

// 处理待审核文件页码变化
const handlePendingCurrentChange = (val) => {
    pendingCurrentPage.value = val
    fetchPendingFiles()
}


// 下载文件
const handleDownload = (file) => {
    // 构建下载链接
    const baseUrl = import.meta.env.VITE_APP_API_URL + import.meta.env.VITE_APP_BASE_API || window.location.origin
    const downloadUrl = `${baseUrl}/v1/file/download?id=${file.id}&code=${file.accessCode}`

    const token = localStorage.getItem('token')
    const clientIP = localStorage.getItem('ClientIP')
    // 下载文件
    http.downloadFile(downloadUrl, {}, { token, clientIP }).then(response => {
        // 检查响应类型是否为JSON (表示出现异常)
        const contentType = response.headers['content-type'] || '';
        if (contentType.includes('application/json')) {
            // 处理JSON响应（异常情况）
            if (response.data instanceof Blob) {
                // 如果是Blob类型，需要先转换为文本
                return response.data.text().then(text => {
                    try {
                        const result = JSON.parse(text);
                        // console.log('解析的JSON结果:', result);
                        // 显示错误信息
                        ElMessage.error(result.msg || '下载失败');
                    } catch (parseError) {
                    }
                });
            } else if (typeof response.data === 'object') {
                // 如果已经是对象（可能某些HTTP客户端会自动解析JSON）
                // console.log('JSON对象响应:', response.data);
                ElMessage.error(response.data.msg || '下载失败');
                // throw new Error(response.data.msg || '下载失败');
            }
        }

        // 正常下载处理流程
        const blob = response.data;
        const disposition = response.headers['content-disposition'] || '';
        let fileName = 'downloaded_file';
        const match = disposition.match(/filename="?([^"]+)"?/);
        if (match) {
            fileName = decodeURIComponent(match[1]);
        }

        // 触发下载
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);

        // 显示下载成功提示
        ElMessage.success('文件下载成功');
    })
}

// 编辑文件
const handleEdit = (file) => {
    fileForm.value = {
        id: file.id,
        fileName: file.fileName,
        accessCode: file.accessCode,
        status: file.status,
        auditStatus: file.auditStatus
    }
    dialogVisible.value = true
}

// 删除文件
const handleDelete = (file) => {
    ElMessageBox.confirm(
        `确定要删除文件 ${file.fileName} 吗？`,
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 调用删除API
        http.delete(`${list.list_admin_api.deleteFile}/${file.id}`)
            .then(response => {
                if (response.code === 200) {
                    ElMessage.success('文件已删除')
                    fetchFileList() // 重新加载文件列表
                } else {
                    ElMessage.error('删除文件失败：' + response.data.msg)
                }
            })
            .catch(error => {
                console.error('删除文件出错：', error)
                ElMessage.error('删除文件失败，请稍后重试')
            })
    }).catch(() => {
        // 取消删除
    })
}

// 预览对话框相关
const previewDialogVisible = ref(false)
const previewFile = ref(null)
const previewUrl = ref('')
const previewLoading = ref(false)
const textLoading = ref(false)
const textContent = ref('')
const archiveContents = ref([])

// 判断是否为文本文件
const isTextFile = (fileName) => {
    const ext = fileName.toLowerCase().split('.').pop()
    return ['txt', 'log', 'csv', 'md', 'json', 'xml', 'html', 'htm'].includes(ext)
}

// 判断是否为代码文件
const isCodeFile = (fileName) => {
    const ext = fileName.toLowerCase().split('.').pop()
    return ['js', 'ts', 'java', 'py', 'c', 'cpp', 'cs', 'php', 'rb', 'go', 'swift', 'sh', 'bat', 'css', 'scss', 'less', 'vue', 'jsx', 'tsx'].includes(ext)
}

// 根据文件扩展名获取文件类型
const getFileTypeByExt = (fileName) => {
    if (!fileName) return '未知'
    const ext = fileName.toLowerCase().split('.').pop()

    // 文档类型
    if (['pdf', 'txt', 'md', 'rtf'].includes(ext)) {
        return '文档'
    }
    // 图片类型
    else if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp'].includes(ext)) {
        return '图片'
    }
    // 视频类型
    else if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm'].includes(ext)) {
        return '视频'
    }
    // 音频类型
    else if (['mp3', 'wav', 'ogg', 'flac', 'aac', 'm4a'].includes(ext)) {
        return '音频'
    }
    // 压缩包类型
    else if (['zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'jar'].includes(ext)) {
        return '压缩包'
    }
    // 代码类型
    else if (isCodeFile(fileName)) {
        return '代码'
    }
    // 默认类型
    return '其他'
}

// 根据文件扩展名获取标签类型
const getFileTypeTagByExt = (fileName) => {
    if (!fileName) return ''
    const ext = fileName.toLowerCase().split('.').pop()

    // 文档类型
    if (['pdf', 'txt', 'md', 'rtf'].includes(ext)) {
        return 'primary'
    }
    // 图片类型
    else if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp'].includes(ext)) {
        return 'success'
    }
    // 视频类型
    else if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm'].includes(ext)) {
        return 'warning'
    }
    // 音频类型
    else if (['mp3', 'wav', 'ogg', 'flac', 'aac', 'm4a'].includes(ext)) {
        return 'danger'
    }
    // 压缩包类型
    else if (['zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'jar'].includes(ext)) {
        return 'info'
    }
    // 默认类型
    return ''
}

// 获取代码语言类名
const getCodeLanguageClass = (fileName) => {
    const ext = fileName.toLowerCase().split('.').pop()
    return `language-${ext}`
}

// 加载文本内容
const loadTextContent = (file) => {
    textLoading.value = true
    textContent.value = ''

    // 使用fetch获取文本内容
    fetch(previewUrl.value)
        .then(response => response.text())
        .then(content => {
            textContent.value = content
        })
        .catch(error => {
            console.error('加载文本内容失败:', error)
            ElMessage.error('加载文本内容失败')
        })
        .finally(() => {
            textLoading.value = false
        })
}

// 加载压缩包内容
const loadArchiveContents = (file) => {
    // 调用后端API获取压缩包内容
    ElMessage.info('正在加载压缩包内容...')
    archiveContents.value = []
    previewLoading.value = true

    // 构建请求参数
    const params = {
        id: file.id,
        code: file.accessCode
    }

    // 调用API获取压缩包内容
    http.get(list.list_file_api.archiveContents, params)
        .then(response => {
            if (response.code === 200 && response.data) {
                archiveContents.value = response.data
                if (archiveContents.value.length === 0) {
                    ElMessage.warning('压缩包为空或无法解析内容')
                }
            } else {
                ElMessage.error(response.msg || '获取压缩包内容失败')
            }
        })
        .catch(error => {
            console.error('获取压缩包内容失败:', error)
            ElMessage.error('获取压缩包内容失败，请稍后重试')
        })
        .finally(() => {
            previewLoading.value = false
        })
}

// 预览文件
const handlePreview = (file) => {
    previewFile.value = file
    previewLoading.value = true
    previewDialogVisible.value = true
    textContent.value = ''
    archiveContents.value = []

    // 构建预览链接 - 使用专门的预览API而不是下载API
    const baseUrl = import.meta.env.VITE_APP_API_URL + import.meta.env.VITE_APP_BASE_API || window.location.origin
    previewUrl.value = `${baseUrl}/v1/file/preview?id=${file.id}&code=${file.accessCode}`

    // 获取token和客户端IP，用于授权访问
    const token = localStorage.getItem('token')
    const clientIP = localStorage.getItem('ClientIP')

    // 添加token到URL以授权访问
    if (token) {
        previewUrl.value += `&token=${token}`
    }

    // 添加客户端IP
    if (clientIP) {
        previewUrl.value += `&clientIP=${clientIP}`
    }

    // 对于PDF文档，预览加载完成后隐藏加载状态
    if (file.fileType === 'document' && file.fileName.toLowerCase().endsWith('.pdf')) {
        // 设置一个定时器，在iframe加载完成后隐藏加载状态
        setTimeout(() => {
            previewLoading.value = false
        }, 1500)
    }

    // 对于文本和代码文件，自动加载内容
    if ((isTextFile(file.fileName) || isCodeFile(file.fileName)) && file.fileType === 'document') {
        loadTextContent(file)
    }

    // 对于压缩包文件，自动加载压缩包内容
    if (file.fileType === 'archive') {
        loadArchiveContents(file)
    } else {
        // 延迟关闭加载状态，给预览内容加载时间
        setTimeout(() => {
            previewLoading.value = false
        }, 600)
    }
}

// 审核通过
const handleApprove = (file) => {
    ElMessageBox.confirm(
        `确定通过文件 ${file.fileName} 的审核吗？`,
        '审核确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info',
        }
    ).then(() => {
        // 构建请求参数
        const params = {
            fileId: file.id,
            auditStatus: 'approved',
            status: 'active',
            audit_remark: '通过审核'
        }

        // 调用更新API
        http.post(list.list_admin_api.updateFileStatus, params)
            .then(response => {
                console.log('change:', response)
                if (response.code === 200) {
                    ElMessage.success('已通过文件审核')
                    fetchPendingFiles() // 重新加载待审核文件列表
                    fetchFileList() // 重新加载文件列表
                } else {
                    ElMessage.error('审核操作失败：' + response.data.msg)
                }
            })
            .catch(error => {
                console.error('审核操作出错：', error)
                ElMessage.error('审核操作失败，请稍后重试')
            })
    }).catch(() => {
        // 取消操作
    })
}

// 审核拒绝
const handleReject = (file) => {
    rejectForm.value = {
        fileId: file.id,
        reasonType: '',
        detail: ''
    }
    rejectDialogVisible.value = true
}

// 处理拒绝原因类型变化
const handleReasonTypeChange = (value) => {
    // 根据选择的类型预填写详细说明
    switch (value) {
        case 'violation':
            rejectForm.value.detail = '该文件包含违规内容，不符合平台规定。'
            break
        case 'copyright':
            rejectForm.value.detail = '该文件可能侵犯他人知识产权，无法通过审核。'
            break
        case 'malware':
            rejectForm.value.detail = '该文件可能包含恶意软件或病毒，存在安全风险。'
            break
        default:
            rejectForm.value.detail = ''
    }
}

// 提交文件表单
const submitFileForm = () => {
    fileFormRef.value.validate((valid) => {
        if (valid) {
            // 构建请求参数
            const params = {
                fileId: fileForm.value.id,
                fileName: fileForm.value.fileName,
                status: fileForm.value.status,
                auditStatus: fileForm.value.auditStatus,
                accessCode: fileForm.value.accessCode,
            }

            // 调用更新API
            http.post(list.list_admin_api.updateFileStatus, params)
                .then(response => {
                    if (response.code === 200) {
                        dialogVisible.value = false
                        ElMessage.success('文件信息已更新')
                        fetchFileList() // 重新加载文件列表
                    } else {
                        ElMessage.error('更新文件失败：' + response.data.msg)
                    }
                })
                .catch(error => {
                    console.error('更新文件出错：', error)
                    ElMessage.error('更新文件失败，请稍后重试')
                })
        }
    })
}

// 提交拒绝表单
const submitRejectForm = () => {
    rejectFormRef.value.validate((valid) => {
        if (valid) {
            // 构建请求参数
            const params = {
                fileId: rejectForm.value.fileId,
                auditStatus: 'rejected',
                auditRemark: `${rejectForm.value.reasonType}: ${rejectForm.value.detail}`
            }

            // 调用更新API
            http.post(list.list_admin_api.updateFileStatus, params)
                .then(response => {
                    console.log('reject:', response)
                    if (response.code === 200) {
                        rejectDialogVisible.value = false
                        ElMessage.success('已拒绝文件上传')
                        fetchPendingFiles() // 重新加载待审核文件列表
                    } else {
                        ElMessage.error('拒绝操作失败：' + response.data.msg)
                    }
                })
                .catch(error => {
                    console.error('拒绝操作出错：', error)
                    ElMessage.error('拒绝操作失败，请稍后重试')
                })
        }
    })
}

// 生成随机访问码
const generateAccessCode = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    let result = ''
    for (let i = 0; i < 4; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return result
}

onMounted(() => {
    // 初始化加载数据
    fetchFileList()
    fetchPendingFiles()
})
</script>

<style scoped>
.admin-files {
    padding: 20px;
}

.page-title {
    margin-bottom: 20px;
    font-size: 24px;
    color: #303133;
}

.toolbar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    align-items: center;
}

.search-input {
    width: 300px;
}

.filter-group {
    display: flex;
    gap: 15px;
    align-items: center;
}

.filter-label {
    font-size: 14px;
    color: #606266;
    white-space: nowrap;
}

.filter-select {
    width: 140px;
}

.file-name-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.file-icon {
    font-size: 18px;
}

.file-name {
    display: inline-block;
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.access-code {
    font-family: monospace;
    font-weight: bold;
    letter-spacing: 2px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.file-tabs {
    margin-top: 20px;
    margin-bottom: 20px;
}

/* 文件信息栏样式 */
.file-info-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 15px;
    border: 1px solid #e4e7ed;
}

.file-info {
    display: flex;
    align-items: center;
    flex: 1;
}

.file-info .file-icon {
    margin-right: 10px;
    color: #409EFF;
}

.file-info .file-name {
    font-weight: bold;
    margin-right: 15px;
    max-width: 400px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.file-info .file-type-tag {
    margin-right: 15px;
}

.file-info .file-size {
    color: #909399;
    font-size: 0.9em;
}

.file-actions {
    display: flex;
    gap: 10px;
}

.image-preview {
    text-align: center;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: auto;
}

.image-preview img {
    max-width: 100%;
    max-height: calc(100vh - 180px);
    object-fit: contain;
}

.document-preview {
    width: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.document-preview iframe {
    flex: 1;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #fff;
}

.text-preview,
.code-preview {
    width: 100%;
    flex: 1;
    overflow: auto;
    border: 1px solid #eee;
    border-radius: 4px;
    background-color: #fff;
}

.text-content,
.code-content {
    padding: 15px;
    white-space: pre-wrap;
    font-family: monospace;
    font-size: 14px;
    line-height: 1.5;
}

.text-fallback,
.code-fallback,
.document-fallback {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300px;
    color: #909399;
}

.document-fallback p {
    margin: 20px 0;
}

.video-preview,
.audio-preview {
    width: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    /* 移除这里的padding，使用.preview-content中的统一padding */
}

.video-preview video {
    max-height: calc(100vh - 200px);
    max-width: 100%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    display: block;
    margin: 0 auto;
}

.audio-preview audio {
    width: 90%;
    max-width: 600px;
    margin: 20px auto 0;
    display: block;
}

.archive-preview {
    width: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.archive-info {
    text-align: center;
    padding: 20px;
    border-bottom: 1px solid #eee;
}

.archive-info h3 {
    margin: 10px 0;
}

.archive-contents {
    margin-top: 20px;
    flex: 1;
    overflow: auto;
}

.archive-contents h4 {
    margin-bottom: 10px;
}

.preview-actions {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 10px;
}

/* 预览对话框样式 */
.preview-dialog :deep(.el-dialog__body) {
    padding: 0;
}

.preview-container {
    height: 70vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.preview-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.preview-content {
    flex: 1;
    /* overflow: auto; */
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f8f9fa;
    /*padding: 20px;*/
}

/* 文本预览样式 */
.text-preview,
.code-preview {
    width: 100%;
    height: 100%;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fff;
    overflow: auto;
    box-shadow: inset 2px 8px 10px 4px rgba(0, 0, 0, 0.1);
}

.text-content,
.code-content {
    padding: 16px;
    margin: 0;
    white-space: pre-wrap;
    word-break: break-all;
    font-family: Consolas, Monaco, 'Andale Mono', monospace;
    font-size: 14px;
    line-height: 1.5;
}

.code-content {
    background-color: #282c34;
    color: #abb2bf;
}

.text-fallback,
.code-fallback,
.document-fallback {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    padding: 15px;
    width: 100%;
}

/* 图片预览样式 */
.image-preview img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* PDF预览样式 */
.pdf-container {
    width: 100%;
    height: 100%;
    /* overflow: auto; */
    border-radius: 4px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
}

/* 视频预览样式 */
.video-container {
    width: 90%;
    max-height: 100%;
    border-radius: 4px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.video-preview video {
    width: 100%;
    display: block;
    border-radius: 4px;
}

/* 音频预览样式 */
.audio-preview {
    /* width: 100%; */
    display: flex;
    justify-content: center;
    align-items: center;
}

.audio-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 15px;
    padding: 15px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
    width: 90%;
    margin: 0 auto;
}

.audio-icon {
    color: #409EFF;
}

/* 压缩包预览样式 */
.archive-preview {
    width: 100%;
    height: 100%;
    background-color: #fff;
    border-radius: 4px;
    /* overflow: auto; */
}

.archive-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
    text-align: center;
}

.archive-contents {
    margin-top: 20px;
}

.archive-actions {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin-top: 20px;
}

.other-preview {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    /* padding: 20px; */
}
</style>